package utils

import (
	"strings"
)

/**
 * @Description
 * @Author huan.wang
 * @Date 2021/4/30 10:35 上午
 **/

func CheckTopic(topic string, filter string) bool {
	filters := strings.Split(filter, "/")
	topics := strings.Split(topic, "/")
	var matched = true
	if len(topics) < len(filters) {
		matched = false
	} else {
		for lIndex, t := range topics {
			if lIndex == 0 && len(t) > 0 && t[0] == '$' {
				if t != filters[0] {
					matched = false
					break
				}
			}
			if lIndex == 0 && len(filters) > 0 && len(filters[0]) > 0 && filters[0][0] == '$' {
				if t != filters[0] {
					matched = false
					break
				}
			}
			if len(filters) <= lIndex {
				matched = false
				break
			}
			if filters[lIndex] == "#" {
				break
			}
			if filters[lIndex] == "+" {
				if lIndex == len(topics)-1 && len(filters)-1 > lIndex {
					matched = false
					break
				}
				continue
			}
			if len(filters[lIndex]) != len(t) {
				matched = false
				break
			}
			for sIndex, tt := range t {
				if filters[lIndex][sIndex] == '$' {
					continue
				}
				f := []rune(filters[lIndex])
				if f[sIndex] != tt {
					matched = false
					break
				}
			}
		}
	}
	return matched
}
